import type { ComponentClass } from 'react';
import React, { useMemo, useCallback } from 'react';
import DataEditCell from 'gantd/lib/data-edit-cell';
import { compose, mapProps } from 'recompose';
import classnames from 'classnames';
import { Icon } from 'antd';
import styles from './styles.less';

interface WrapperComponentProps {
  onLoupeClick?: () => void;
  [propsname: string]: any;
}

const withLoupe = () =>
  compose(
    (WrapperComponent: ComponentClass) => (props: WrapperComponentProps) => {
      const { renderReadElement, onLoupeClick, disabled, showLoupe = true, ...restProps } = props;

      const hackTreeSelect = useMemo(() => {
        const { componentType, multiple } = restProps;
        return componentType == 'TreeSelect' && multiple;
      }, [restProps]);

      const handleLoupeClick = useCallback(() => {
        if (disabled) return;
        onLoupeClick && onLoupeClick();
      }, [disabled, onLoupeClick]);

      return (
        <DataEditCell renderText={renderReadElement} {...restProps}>
          {({ onEnter, ...childProps }) => {
            return (
              <div className={classnames(styles.loupeSelectorWrap, showLoupe ? styles.showLoupe : '')}>
                <div
                  className={hackTreeSelect ? classnames(styles.selectWrap, styles.treeSelectArrow) : styles.selectWrap}
                >
                  <WrapperComponent onKeyDown={onEnter} disabled={disabled} {...childProps} />
                  {hackTreeSelect && (
                    <Icon
                      className={
                        disabled ? classnames(styles.extraArrowIcon, styles.suffixIconDisabled) : styles.extraArrowIcon
                      }
                      type="down"
                    />
                  )}
                  {showLoupe && (
                    <Icon
                      className={
                        disabled
                          ? classnames(styles.searchIcon, styles.searchIconDisabled, 'loupeIconDisabled')
                          : styles.searchIcon
                      }
                      type="search"
                      onClick={handleLoupeClick}
                    />
                  )}
                </div>
              </div>
            );
          }}
        </DataEditCell>
      );
    },
    mapProps(({ onLoupeClick, ...props }: WrapperComponentProps) => props),
  );

export default withLoupe;
